<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptions" class="is--card">
      <template #form="{ form }">
        <VSelect v-model="form.supplier_name" placeholder="供应商" type="supplierName" allow-create style="min-width: 200px" multiple collapse-tags />
        <VBatchInput v-model="form.purchase_no" placeholder="采购单号" clearable class="w-44" @search="query" />
        <VBatchInput v-model="form.sku" placeholder="SKU" clearable class="w-44" @search="query" />
        <VSelect v-model="form.month" placeholder="货款所属期" :options="monthOptins" style="min-width: 160px" />
        <VSelect v-model="form.company_id" placeholder="公司主体" :options="options.company_id" multiple collapse-tags style="min-width: 210px" />
        <VCascader v-model="form.department_name" placeholder="需求部门" type="department" multiple collapse-tags checkStrictly style="min-width: 160px" />
        <VSelect v-model="form.time_from" placeholder="日期来源" :options="options.time_from" multiple collapse-tags style="min-width: 210px" />
        <VSelect v-model="form.period_id" placeholder="结算方式" type="period" multiple collapse-tags style="min-width: 220px" />
        <VSelect v-model="form.currency" placeholder="币种" :options="options.currency" multiple collapse-tags style="min-width: 160px" />
        <VCascader v-model="form.purchase_user_id" placeholder="采购人员" multiple collapse-tags style="min-width: 160px" />
        <VGroup>
          <el-select v-model="form.snapshot_type" class="w-28" @change="form.snapshot_cycle = []">
            <el-option label="周历史周期" :value="1"></el-option>
            <el-option label="月历史周期" :value="2"></el-option>
          </el-select>
          <VSelect v-show="form.snapshot_type === 1" v-model="form.snapshot_cycle" placeholder="请选择" select :options="cycleOptions1" multiple collapse-tags
            style="min-width: 160px" />
          <VSelect v-show="form.snapshot_type === 2" v-model="form.snapshot_cycle" placeholder="请选择" select :options="cycleOptions2" multiple collapse-tags
            style="min-width: 160px" />
        </VGroup>
        <VGroup>
          <el-select v-model="form.dateRange.type" style="width: 130px">
            <el-option label="结算日期" value="settlement_time"></el-option>
            <el-option label="预计到货时间" value="expect_delivery_time"></el-option>
            <el-option label="本次入库时间" value="inbound_time"></el-option>
          </el-select>
          <VDate v-model="form.dateRange.value" />
        </VGroup>
       <VSelect v-model="form.is_payment " placeholder="是否需要付款" :options="options.is_payment" multiple collapse-tags style="min-width: 160px" /> 
      </template>
      <template #toolbar_btns>
        <el-tabs v-model="type" class="w-full" @tab-click="typeChange">
          <el-tab-pane v-for="(d, i) in typeOptions" :key="i" :label="d.label" :name="d.value"></el-tab-pane>
        </el-tabs>
        <VButton v-if="type" auth="/purchase/manage/estimate/remark" :loading="loadings.remark" @click="handleBatch('remark')">批量备注
        </VButton>
        <VButton v-if="type === 2" auth="/purchase/manage/estimate/submit" :loading="loadings.confirm" @click="handleBatch('confirm')">批量确认</VButton>
        <VButton v-if="type" auth="/purchase/manage/estimate/updateTime" :loading="loadings.updateTime" @click="handleBatch('updateTime')">批量修改结算日期
        </VButton>
        <VTotal :data="total" :options="totalOptions" class="ml-auto" />
        <VExport auth="/purchase/manage/estimate/derive" mainKey="cpd_id" :name="['purchase-estimate-payable', 'purchase_payable', 'purchase-estimate'][type]" :tableRef="tableRef"
          task class="ml-auto" />
      </template>
    </VTable>
    <Time ref="timeRef" />
    <VLog ref="logRef" />
  </VPage>
</template>
  
<script setup lang="jsx" name="Account">
import api from './api'
import Time from './components/Time'
import { getOption } from '@/api/public'
import { getYearMonth } from '@/utils'
import { ElMessage, ElMessageBox } from 'element-plus'
import VTotal from '@/components/VTotal'
import { resMessage } from '@/utils/res'
import { computed } from 'vue'

const baseName = 'cash_plan'
const tableRef = ref()
const logRef = ref()
const loadings = reactive({})
// 查询
const query = () => {
  tableRef?.value.query()
}

// 获取options
const options = ref({})
const date = new Date()
const year = date.getFullYear()
const monthOptins = getYearMonth([year - 1, year])
const typeOptions = ref([{ label: '全部', value: 0 },{ label: '采购单应付余额', value: 1 }, { label: '采购单预估应付', value: 2 }])
Promise.all([
  getOption({ type: baseName }).then(res => res.data),
  Promise.resolve({ test: [{ label: '没有数据', value: 1 }] })
]).then(res => {
  options.value = res.reduce((acc, cur) => (((acc = { ...acc, ...cur }), acc)), {})
})

const cycleOptions1 = ref([])
const cycleOptions2 = ref([])
api.cycle({type: 1}).then(res => {
  cycleOptions1.value = res.data.map(d => ({label: d, value: d}))
})
api.cycle({type: 2}).then(res => {
  cycleOptions2.value = res.data.map(d => ({label: d, value: d}))
})

// 批量操作
const handleBatch = (name) => {
  const selection = tableRef.value.$table.getCheckboxRecords()
  if (!selection.length) {
    ElMessage.warning('请先选择行')
    return
  }
  const cpd_ids = selection.map(d => d.cpd_id)
  const showLoading = () => loadings[name] = true
  const closeLoading = () => loadings[name] = false
  const handle = {
    confirm: () => {
      showLoading()
      api.confirm({ cpd_ids }).then(res => {
        ElMessage.success('操作成功')
        query()
      }).finally(closeLoading)
    },
    updateTime: () => {
      const settlement = ref()
      ElMessageBox({
        title: '修改结算日期',
        message: () => <el-date-picker v-model={settlement.value} placeholder="日期选择" type="date" value-format="YYYY-MM-DD" class="w-full" />
      }).then(() => {
        api.updateTime({cpd_ids, settlement_time: settlement.value, type: type.value}).then(res => {
          resMessage({
            res,
            success: () => {
              ElMessage.success('操作成功')
              query()
            }
          })
        }).finally(closeLoading)
        })
    },
    remark: () => {
      ElMessageBox.prompt('备注', '批量修改备注', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValidator: (val) => !val ? '不能为空' : true,
        inputType: 'textarea',
      })
        .then(({ value }) => {
          showLoading()
          api.remark({ cpd_ids, remark: value, type: type.value }).then(res => {
            resMessage({
              res,
              success: () => {
                ElMessage.success('操作成功')
                query()
              }
            })
          }).finally(closeLoading)
        })
        .catch(() => {
          ElMessage({
            type: 'info',
            message: '取消操作',
          })
        })
    },
  }
  handle[name]()
}

// 单行操作
const timeRef = ref()
const handleRow = (name, row, rowIndex) => {
  const { cpd_id, sku, purchase_no } = row
  const showLoading = () => loadings[name + rowIndex] = true
  const closeLoading = () => loadings[name + rowIndex] = false
  const handle = {
    confirm: () => {
      showLoading()
      api.confirm({ cpd_ids: [cpd_id] }).then(res => {
        ElMessage.success('操作成功')
        query()
      }).finally(closeLoading)
    },
    inboundTime: () => {
      timeRef?.value.open({ cpd_id, sku, purchase_no })
    },
    updateTime: () => {
      const settlement = ref(row.settlement_time)
      ElMessageBox({
        title: '修改结算日期',
        message: () => <el-date-picker v-model={settlement.value} placeholder="日期选择" type="date" value-format="YYYY-MM-DD" class="w-full" />
      }).then(() => {
        api.updateTime({cpd_ids: [cpd_id], settlement_time: settlement.value, type: type.value}).then(res => {
          resMessage({
            res,
            success: () => {
              ElMessage.success('操作成功')
              query()
            }
          })
        }).finally(closeLoading)
        })
    },
    log: () => {
      logRef?.value.open({ log_type: 'cash_plan_detail', cpd_id })
    },
  }
  handle[name]()
}

const type = ref(0)
const totalOptions = computed(() => {
  const opts = [
    { title: '采购未税价总额', key: 'total_price_untaxed' }, 
    { title: '未税报价总额', key: 'total_price' }, 
    { title: '采购含税价总额', key: 'total_price_tax' }, 
    { title: '未付总金额', key: 'unpayment_price' },
    { title: '入库总金额', key: 'inbound_price' },
  ]
  const payable_price = { title: '总应付余额', key: 'payable_price' }
  if([0, 2].includes(type.value)) {
    opts.push(payable_price)
  }
  const estimate_price = { title: '总预估应付', key: 'estimate_price' }
  if([0, 1].includes(type.value)) {
    opts.push(estimate_price)
  }
  return opts
})
const getColumns = (t = type.value) => {
  const visible = [0 , 2].includes(t)
  return [
    { type: 'checkbox', width: 40, fixed: 'left' },
    { title: '采购单', field: 'purchase_no', width: 140 },
    { title: 'sku', field: 'sku', width: 100, slots: {
      default: ({row}) => <VText value={row.sku} line={1} />
    }  },
    { title: '采购人员', field: 'purchase_user_name', width: 120, slots: {
      default: ({row}) => <VText value={row.purchase_user_name} line={2} />
    } },
    { title: '供应商名称', field: 'supplier_name', width: 120, slots: {
      default: ({row}) => <VText value={row.supplier_name} line={3} />
    } },
    { title: '类型', field: 'detail_type_name', width: 80 },
    { title: '结算方式', field: 'period_name', width: 140, line: 2 },
    { title: '账期类型', field: 'config_way_name', width: 140 },
    { title: '账期比例', field: 'percent', width: 140,slots:{default:({row})=>(<div>{row?.percent||0}%</div>)} },
    { title: '需求部门', field: 'department_name', width: 120, slots: {
      default: ({row}) => <VText value={row.department_name} line={3} />
    } },
    { title: '贷款所属期', field: 'month', width: 100 },
    // { title: '入库时间', field: 'inbound_time', width: 160 },
    { title: '预计到货时间', field: 'expect_delivery_time', width: 140 },
    { title: '本次入库时间', field: 'inbound_time', width: 180 },
    { title: '结算日期', field: 'settlement_time', width: 100 },
    { title: '日期来源', field: 'time_from_name', width: 100, },
    { title: '币种', field: 'currency', width: 80 },
    { field: 'unit_price', width: 120, slots: {
      header: () => <span>下单数<br/>本次入库数<br/>总入库数<br/>SKU未入库数</span>,
      default: ({row}) => <div>
        <VText value={row.purchase_num} />
        <VText value={row.inbound_num} />
        <VText value={row.sku_inbound_num} />
        <VText value={row.sku_un_inbound_num} />
      </div>,
    } },
    { field: 'unit_price', width: 100, slots: {
      header: () => <span>采购未税价<br/>未税报价<br/>采购含税价</span>,
      default: ({row}) => <div>
        <VText value={row.unit_untaxed_price} />
        <VText value={row.unit_price} />
        <VText value={row.unit_price_tax} />
      </div>,
    } },
    { title: '供应商税点', field: 'tax_rate', width: 96 },
    { field: 'currency', width: 120, slots: {
      header: () => <span>采购未税价总额<br/>未税报价总额<br/>采购含税价总额</span>,
      default: ({row}) => <div>
        <VText value={row.total_price_untaxed} />
        <VText value={row.total_price} />
        <VText value={row.total_price_tax} />
      </div>,
    } },
    {
      title: '分摊计算金额',
      align:'center',
       children: [
        { title: '应付金额(采购应付)', field: 'payable_payment_price', width: 95, visible: [0, 1].includes(t) },
        { title: '应付金额(采购预估)', field: 'estimate_payment_price', width: 95, visible: [0, 2].includes(t) },
        { width: 100, slots: {
          header: () => <span>应付运费<br/>应付货款<br/>应付优惠</span>,
          default: ({row}) => <div>
            <VText value={row.payable_before_tracking_price} />
            <VText value={row.payable_goods_price} />
            <VText value={row.payable_discount_price} />
          </div>,
        } },
        {  width: 120, slots: {
          header: () => <span>应付下单后运费<br/>应付售后<br/>应付折扣</span>,
          default: ({row}) => <div>
            <VText value={row.payable_tracking_price} />
            <VText value={row.payable_after_sale_price} />
            <VText value={row.payable_preferential_price} />
          </div>,
        } },
        {  width: 120, slots: {
          header: () => <span>额度退款金额<br/>库内退货金额<br/>实际退款金额<br/>完结金额</span>,
          default: ({row}) => <div>
            <VText value={row.s_pre_refund_total_price} />
            <VText value={row.s_return_total_price} />
            <VText value={row.s_refund_total_price} />
            <VText value={row.complete_price} />
          </div>,
        } },
        { title: '应付余额(采购应付）', field: 'payable_price', width: 95, visible: [0, 1].includes(t) },
        { title: '应付余额(采购预估)', field: 'estimate_price', width: 95, visible: [0, 2].includes(t) },
        {  width: 120, slots: {
          header: () => <span>分摊已付运费<br/>分摊已付货款<br/>分摊已付优惠</span>,
          default: ({row}) => <div>
            <VText value={row.payment_before_tracking_price} />
            <VText value={row.payment_goods_price} />
            <VText value={row.payment_discount_price} />
          </div>,
        } },
        {  width: 150, slots: {
          header: () => <span>分摊已付下单后运费<br/>分摊已付售后<br/>分摊已付折扣</span>,
          default: ({row}) => <div>
            <VText value={row.payment_tracking_price} />
            <VText value={row.payment_after_sale_price} />
            <VText value={row.payment_preferential_price} />
          </div>,
        } },
       ]
    },
    {
      title: '采购单SKU总金额',
      align:'center',
       children: [
        { title: '下单金额', field: 'purchase_price', width: 90 },
        { title: '入库金额', field: 'inbound_price', width: 90 },
        { title: '未入库金额', field: 'uninbound_price', width: 90 },
        { title: '已付金额', field: 'payment_price', width: 90 },
        { title: '未付金额', field: 'unpayment_price', width: 90 },
        { title: '库内退货金额', field: 'return_price', width: 110 },
        { title: '完结金额', field: 'sku_complete_price', width: 110 },


       ]
    },

    // { title: '应付余额', field: 'payable_price', width: 90, visible: [0, 1].includes(t) },
    // { title: '退款金额', field: 'refund_price', width: 90 },
    // { title: '预估应付', field: 'estimate_price', width: 100, visible },
    {  width: 150, slots: {
      header: () => <span>实际退款金额<br/>额度退款金额</span>,
      default: ({row}) => <div>
        <VText value={row.sku_actual_refund_price} />
        <VText value={row.sku_pre_refund_price} />
      </div>,
    } },    
    {  width: 150, slots: {
      header: () => <span>下单后运费<br/>折扣<br/>售后</span>,
      default: ({row}) => <div>
        <VText value={row.sku_tracking_price} />
        <VText value={row.sku_preferential_price} />
        <VText value={row.sku_after_sale_price} />
      </div>,
    } },   
    { title: '公司主体', field: 'company_name', width: 140, slots: {
      default: ({row}) => <VText value={row.company_name} line={2} />
    } },
    // { title: '状态', field: 'detail_status_name', width: 100, visible },
    { title: '备注', field: 'remark', width: 140, slots: {
      default: ({row}) => <VText value={row.remark} line={2} />
    } },
    {
      title: '操作', width: 180, fixed: 'right', visible: !!t, slots: {
        default: ({ row, rowIndex }) => {
          const { detail_status, detail_type } = row
          // 状态1已确认2未确认3异常4已全部付款
          return <div class='nm flex flex-wrap gap-x-2 gap-y-1'>
            {[1, 3].includes(detail_type) && [2].includes(detail_status) ? <VButton auth="/purchase/manage/estimate/submit" link type="primary" loading={loadings['confirm' + rowIndex]} onClick={() => handleRow('confirm', row, rowIndex)}>确认</VButton> : ''}
            {[1, 3].includes(detail_type) && [3].includes(detail_status) ? <VButton  auth="/purchase/manage/estimate/inboundTime" link type="primary" loading={loadings['inboundTime' + rowIndex]} onClick={() => handleRow('inboundTime', row, rowIndex)}>填写未到货预计入库时间</VButton> : ''}
            <VButton auth="/purchase/manage/estimate/updateTime" link type="primary" onClick={() => handleRow('updateTime', row, rowIndex)}>修改结算日期</VButton>
            <el-button link type='primary' onClick={() => handleRow('log', row, rowIndex)}>日志</el-button>
          </div>
        }
      }
    }
  ]
}
// 列表配置
const total = ref({})
const tableOptions = reactive({
  border: true,
  showHeaderOverflow: false,
  rowConfig: {height: 96},
  formConfig: {
    data: {
      type: 0,
      snapshot_type: 1,
      is_payment:[2],
      dateRange: { type: 'settlement_time', value: [], range: true },
    }
  },
  columns: getColumns(),
  proxyConfig: {
    autoLoad: false,
    ajax: {
      query: ({ page, form }) => {
        api.total({ ...form, ...page }).then(res => {
          total.value = res.data
        })
        return api.query({ ...form, ...page })
      }
    }
  }
})
const typeChange = ({ paneName }) => {
  const table = tableRef?.value
  if (!table) return
  const form = tableRef.value.getForm()
  table.$table.reloadColumn(getColumns(paneName))
  const timer = setTimeout(() => {
    tableRef?.value.updateScroll()
    clearTimeout(timer)
  }, 500)
  table.setForm({...form,type: paneName })
  query()
}
</script>
  